//
//  Person.m
//  test
//
//  Created by yun on 2018/4/3.
//  Copyright © 2018年 yun. All rights reserved.
//

#import "Person.h"
#import <objc/runtime.h>

@implementation Person

#pragma mark -- 动态方法解析
/*
 resolveInstanceMethod和resolveClassMethod
 
 + (BOOL)resolveInstanceMethod:(SEL)aSEL
 {
 if (aSEL == @selector(resolveThisMethodDynamically)) {
 class_addMethod([self class], aSEL, (IMP) dynamicMethodIMP, "v@:");
 return YES;
 }
 return [super resolveInstanceMethod:aSEL];
 }
 
 v@: 表示 返回值 参数1 参数2
 https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
 
 */


/*
 class_addMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp,
 const char * _Nullable types)
 Class:类 + 方法用self
 IMP:方法实现  class_getMethodImplementation
 */
+ (BOOL)resolveInstanceMethod:(SEL)sel{
    if (sel == @selector(sayHello)) {
        class_addMethod(self, sel, class_getMethodImplementation(self, @selector(dySayHello)), "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
    
}

- (void)dySayHello{
    NSLog(@"hello");
}
/*
 objc_getClass(const char * _Nonnull name) 返回Class
 object_getClass(id _Nullable obj) 返回Class
 参数不同
 
 类对象类型是元类，所以在+ 方法里用object_getClass(self)获取元类
 class_getSuperclass(Class _Nullable cls) 返回Class
 
 */

+ (BOOL)resolveClassMethod:(SEL)sel{
    if (sel == @selector(sayBye)) {
        
        class_addMethod(object_getClass(self), sel, class_getMethodImplementation(object_getClass(self), @selector(dySayBye)), "v@:");
        return YES;
    }
    return [class_getSuperclass(self) resolveClassMethod:sel];
}

+ (void)dySayBye{
    
    NSLog(@"bye");
}




@end
